'use strict';
const db = uniCloud.database();
const orderDBName = 'zhy_order';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	if (event.operateType == 1) {
		// 添加
		return addOrder(event, context)
	} else if (event.operateType == 2) {
		// 修改
		return updateOrder(event, context)
	} else if (event.operateType == 3) {
		// 查询orderId
		return getOrder(event, context)
	}
	//返回数据给客户端
	return event
};
async function addOrder(event, context) {
	return await db.collection(orderDBName).add(event);
}
async function updateOrder(event, context) {
	let order = await getOrder(event)
	if (objIsEmpty(order)) {
		console.log('订单号不存在:' + event.orderId);
		return
	}
	let {
		_id,
		...orderInfo
	} = order
	orderInfo.pay_time = event.pay_time
	orderInfo.status = event.status
	if (!objIsEmpty(event.order_fail_reason)) {
		orderInfo.order_fail_reason = event.order_fail_reason
	}
	return await db.collection(orderDBName).doc(_id).update(event);
}
async function getOrder(event, context) {
	if (objIsEmpty(event) || objIsEmpty(event.orderId)) {
		return null
	}
	let order = await db.collection(orderDBName).where({
		orderId: event.orderId
	}).limit(1).get()
	console.log(JSON.stringify(order));
	return order.data[0];
}

function objIsEmpty(obj) {
	if (obj == undefined || obj == '' || obj == null || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}